package com.mxprojects.gui
{
	import com.mxprojects.constructors.InputConstructor;
	import com.mxprojects.io.CustomEvent;
	import com.mxprojects.io.DeepLinking;
	import com.mxprojects.language.Language;
	import com.mxprojects.language.Word;
	import com.mxprojects.views.Forums;
	import com.mxprojects.views.Search;
	
	import flash.display.Sprite;
	import flash.events.FocusEvent;
	import flash.events.KeyboardEvent;
	import flash.ui.Keyboard;

	public class QuickSearch extends Sprite
	{
		private const LABEL_CSS:String = "quickSearchLabel";
		private const INPUT_CSS:String = "quickSearchInput";
		private const SEARCH_TYPE:String = "p"; //posts
		
		private var quickSearchStyle:Object;
		private var search:InputConstructor;
		
		public function QuickSearch(){
			quickSearchStyle = Styles.css.getStyle(".quickSearch");
			
			search = new InputConstructor(Language.main(Word.QUICK_SEARCH), "", 1, false, 1, LABEL_CSS, INPUT_CSS);
			addChild(search);
			
			//move there where we need to go
			x = quickSearchStyle.x;
			y = quickSearchStyle.y;
			
			//do a quick resize
			resize();
			
			//listen to when the input gets focus/looses it
			search.inputBox.addEventListener(FocusEvent.FOCUS_IN, listenForEnter, false, 0, true);
			search.inputBox.addEventListener(FocusEvent.FOCUS_OUT, stopListening, false, 0, true);
		}
		
		public function resize():void {
			//depending on how it's aligned, we do different things
			switch(quickSearchStyle.align){
				case "right":
					//get the current width and depending on the right margin, move it based on that
					x = Math.round(MXP3.wStage - width - int(Styles.getCleanValue(".quickSearch", "marginRight")));
				break;
				
				case "center":
					x = Math.round(MXP3.wStage/2 - width/2);
				break;
			}
		}
		
		private function listenForEnter(event:FocusEvent):void {
			search.inputBox.addEventListener(KeyboardEvent.KEY_DOWN, checkEnter, false, 0, true);
		}
		
		private function stopListening(event:FocusEvent = null):void {
			search.inputBox.removeEventListener(KeyboardEvent.KEY_DOWN, checkEnter);
			search.inputBox.text = "";
			stage.focus = stage;
		}
		
		private function checkEnter(event:KeyboardEvent):void {
			//if the user hits enter, then search
			if(event.keyCode == Keyboard.ENTER){
				//search posts
				if(Search.forumData == null){
					Forums.load(true, runSearch);
				}else{
					runSearch();
				}
			}
		}
		
		private function runSearch(event:CustomEvent = null):void {
			//make sure the search data is the same as the category info
			Search.forumData = Forums.forumData;
			
			//gotta clear out the old search data that was there
			Search.searchData = null;

			//build the deeplinking
			var linkArray:Array = DeepLinking.createLinkArray(-1, 1, search.inputBox.text, "", SEARCH_TYPE);
			DeepLinking.setLink(Word.SEARCH, linkArray);

			//remove the listener
			stopListening();
		}
	}
}